package com.ljf.captcha;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import com.ljf.captcha.vo.KaptchaVO;
import com.ljf.framework.cache.LjfCacheManager;
import com.ljf.framework.context.LjfContextManager;
import com.ljf.framework.exception.LjfException;
import com.ljf.framework.filter.LjfAbstractFilter;
import com.ljf.framework.filter.LjfFilterAuthStrategy;
import com.ljf.framework.log.LjfLogManager;
import com.ljf.framework.log.LjfLogService;
import com.ljf.framework.result.JsonResult;
import com.ljf.framework.result.JsonResultEnum;
import com.ljf.framework.router.LjfRouter;
import com.ljf.framework.router.LjfRouterConstants;
import com.ljf.framework.router.LjfRouterManager;
import com.ljf.framework.util.LjfJsonUtil;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

import static com.google.code.kaptcha.Constants.KAPTCHA_BORDER;
import static com.google.code.kaptcha.Constants.KAPTCHA_TEXTPRODUCER_FONT_SIZE;

/**
 * 说明：
 *
 * @Auther: lijinfeng
 * @Date: 2024/4/30
 */
public class CaptchaLoginFilter extends LjfAbstractFilter {
    LjfLogService logger = LjfLogManager.getLogger(CaptchaLoginFilter.class);

    @Override
    public Integer getOrder() {
        return 1;
    }

    @Override
    public List getIncludeList() {
        return Arrays.asList(LjfRouterConstants.LOGIN_ROUTER);
    }

    @Override
    public LjfFilterAuthStrategy getBeforeAuthStrategy() {
        return r -> {
            return true;
        };
    }

    @Override
    public LjfFilterAuthStrategy getAuthStrategy() {
        return r -> {
            if(!CaptchaManager.getCaptchaConfig().isOpen()){
                return true;
            }
            String kaptchaCode = (String) LjfContextManager.getRequest().getAttribute("kaptchaCode");
            String imgKey = (String) LjfContextManager.getRequest().getAttribute("imgKey");
            String s = LjfCacheManager.get(CaptchaConstants.LOGIN_CAPTCHA_KEY + imgKey);
            logger.info("提交验证码：" + kaptchaCode + ",缓存验证码：" + s);
            if (!kaptchaCode.equals(s)) {
                throw new LjfException(JsonResultEnum.CAPTCHA_ERROR, "验证码错误");
            }
            return true;
        };
    }


    @Override
    public boolean doCusFilter() {

        return true;

    }


}
